package com.topcent.tioxyc.consumer;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.InspectionData;
import com.topcent.tioxyc.pojo.Order0111;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2024/11/25 09:44
 * @Description:
 */
@Component
@RabbitListener(queues = "StockQuantity")
@Slf4j
public class StockQuantityConsumer {
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";
    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 处理 payload 消息
            //System.out.println("Received payload: " + msg);
            // 在这里执行具体的业务逻辑

            // 在这里处理推送来的数据
            JSONObject payloadJSON = JSONUtil.parseObj(msg);
            String op = payloadJSON.getStr("op");
            String data = payloadJSON.getStr("data");

            if (DATA_CREATE.equals(op)) {
                create(data);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }
    private void create(String data) {

        Header[] headers = ConnmeUtils.createHeaders();
        InspectionData inspectionData = JSONUtil.toBean(data, InspectionData.class);
        if (inspectionData.getInspection_result().equals("NG")){
            return;
        }
        if (inspectionData.getInspection_place().equals("公司仓库")){
            Map<String, Object> parameterCx = new HashMap<>();
            parameterCx.put("app_id", "6690c7633df0f4b90b4ef551");
            parameterCx.put("entry_id", "669df675b02f2a74e35ca2f9");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("_widget_1721628277543", inspectionData.getPurchasing_no());
            hashMap.put("_widget_1721628277558", inspectionData.getPurchasing_hang());
            List<Order0111> order0111s = PurchaseCommunity.
                    queryBased(parameterCx, headers,hashMap, Order0111.class);
            order0111s.getFirst().set_widget_1721978605698(inspectionData.getTotal_qty()+ order0111s.getFirst().get_widget_1721978605698());
            Updatck(headers, order0111s);
        } else {
            Map<String, Object> parameterCx = new HashMap<>();
            parameterCx.put("app_id", "6690c7633df0f4b90b4ef551");
            parameterCx.put("entry_id", "669df675b02f2a74e35ca2f9");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("_widget_1721628277543", inspectionData.getPurchasing_no());
            hashMap.put("_widget_1721628277558", inspectionData.getPurchasing_hang());
            List<Order0111> order0111s = PurchaseCommunity.
                    queryBased(parameterCx, headers, hashMap, Order0111.class);
            if (!order0111s.isEmpty()){
                order0111s.getFirst().set_widget_1721632911791(inspectionData.getTotal_qty()+ order0111s.getFirst().get_widget_1721632911791());
                Updatck(headers, order0111s);
            }
        }

//        Map<String, Object> parameterCx = new HashMap<>();
//        parameterCx.put("app_id", "6690c7633df0f4b90b4ef551");
//        parameterCx.put("entry_id", "6690c891b1ffef3310d1b90d");
//
//        List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCx, headers, inspectionData.getPurchasing_no(), "_widget_1720764561287", SAPPurchaseOrder.class);
//
//        for (SAPPurchaseOrder.Subform subform : sapPurchaseOrders.get(0).get_widget_1720764671480()) {
//            if (subform.get_widget_1720764671534().equals(inspectionData.getPurchasing_hang())){
//                if ( subform.get_widget_1721269068900()==null){
//                    subform.set_widget_1721269068900((double) inspectionData.getTotal_qty());
//                }else {
//                    subform.set_widget_1721269068900(subform.get_widget_1721269068900()+inspectionData.getTotal_qty());
//                }
//                break;
//            }
//        }
//        Map<String, Object> parameterInster = new HashMap<>();
//        parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
//        parameterInster.put("entry_id", "6690c891b1ffef3310d1b90d");
//        parameterInster.put("is_start_trigger", "true");
//        parameterInster.put("data_id", sapPurchaseOrders.get(0).get_id());
//        sapPurchaseOrders.get(0).set_widget_1720764561290(null);
//        sapPurchaseOrders.get(0).set_widget_1720764561295(null);
//        sapPurchaseOrders.get(0).set_widget_1720764561297(null);
//        sapPurchaseOrders.get(0).set_widget_1720764561300(null);
//        for (int i = 0; i < sapPurchaseOrders.get(0).get_widget_1720764671480().size(); i++) {
//            User user1 = JSONUtil.toBean(sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).get_widget_1720764671513(), User.class);
//            User user2 = JSONUtil.toBean(sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).get_widget_1720764671514(), User.class);
//            sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).set_widget_1720764671513(user1.getUsername());
//            sapPurchaseOrders.get(0).get_widget_1720764671480().get(i).set_widget_1720764671514(user2.getUsername());
//        }
//        sapPurchaseOrders.get(0).set_id(null);
//        parameterInster.put("data",ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.get(0)));
//        String jsonSale = JSONUtil.toJsonStr(parameterInster);
//        log.info("修改采购订单收货数量"+jsonSale);
//        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
    }

    private void Updatck(Header[] headers, List<Order0111> order0111s) {
        Map<String, Object> parameterInster002 = new HashMap<>();
        parameterInster002.put("app_id", "6690c7633df0f4b90b4ef551");
        parameterInster002.put("entry_id", "669df675b02f2a74e35ca2f9");
        parameterInster002.put("is_start_trigger", "true");
        parameterInster002.put("data_id", order0111s.getFirst().get_id());
        order0111s.getFirst().set_id(null);
        parameterInster002.put("data", ConnmeUtils.convertEntityToMapNull(order0111s.getFirst()));
        String jsonSale = JSONUtil.toJsonStr(parameterInster002);
        log.info("修改采购改工厂数"+jsonSale);
        JSONObject entries = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
    }
}
